package com.systop.common.modules.security.acegi.taglibs;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.systop.common.modules.dept.model.Dept;
import com.systop.common.modules.dept.service.DeptManager;
import com.systop.common.modules.security.user.UserUtil;
import com.systop.common.modules.security.user.model.User;
/**
 * 用于在页面上显示用户所属部门
 * @author Sam Lee
 *
 */
@SuppressWarnings({"serial"})
public class DisplayUserDeptTag extends BodyTagSupport {
  /**
   * @see BodyTagSupport#doEndTag()
   */
  @Override
  public int doEndTag() throws JspException {
    HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
    User user = UserUtil.getPrincipal(request);
    if (user != null) {
    	;

      try {
        pageContext.getOut().print(
            (userDept(user)!= null) ? userDept(user).getName() : userDept(user).getName());
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return EVAL_PAGE;
  }

  
  /**
   * 加载用户的部门，处理延迟加载问题
   */
  private Dept userDept(User user) {
    ApplicationContext ctx = WebApplicationContextUtils
        .getWebApplicationContext(pageContext.getServletContext());
    DeptManager deptManager = (DeptManager) ctx.getBean("deptManager");
    Dept dept = deptManager.findObject("from Dept d where d.id=?", user.getDept().getId());
    return dept;
  }
}
